<?php 
/***
    Amrita ITEWS - Copyright (C) 2009 Amrita Vishwa Vidyapeetham, Amritapuri.
                                     (http://www.amrita.edu)
    ***************************************************************************
    This file is part of the Amrita ITEWS distribution.
    Amrita ITEWS is free software; you can redistribute it and/or modify it 
    under the terms of the GNU General Public License (version 2) as published 
    by the Free Software Foundation AND MODIFIED BY the Amrita ITEWS exception.
    ***NOTE*** The exception to the GPL is included to allow you to distribute
    a combined work that includes Amrita ITEWS without being obliged to provide
    the source code for proprietary components outside of the Amrita ITEWS
    software. Amrita ITEWS is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details. You should have received a copy of the GNU
    General Public License and the Amrita ITEWS license exception along with 
    Amrita ITEWS if not then it can be viewed here: 
    http://itews.amrita.ac.in/license.html.
    
    Documentation, latest information, license and contact details are at:
    http://itews.amrita.ac.in/
 
    Amrita ITEWS source code can be found at:
    http://code.google.com/p/itews"; 
    
    The initial code-base of Amrita ITEWS was developed by Amrita Vishwa 
    Vidyapeetham as part of the project titled,\"Intelligent & Interactive 
    Telematics using Emerging Wireless Technologies for Transport Systems 
    (ITEWS)\" sponsored by Technology Information Forecasting and Assessment 
    Council (TIFAC), India.
***/
?><?php
class UsersController extends AppController {

	var $name = 'Users';
	var $uses = array('User', 'Aro', 'Aco', 'ArosAco');
	var $components = array('Acl');
	
	function beforeFilter() {
		
		//$this->checkSession();
		date_default_timezone_set("Asia/Calcutta");
		//$this->checkCookies();
		$this->setAutoIncremetsForModelObjects();
		
	}

	function login() {
	
		if(isset($this->params['url']['continue'])){				
			$this->set('continue', $this->params['url']['continue']);
		}
		if(empty($this->data)) {
			//$this->Session->setFlash('Please try again.', 'message_error');
			$this->render('login', 'nomenu');
		}
		//Don't show the error message if no data has been submitted.
		//$this->set('error', false);
		
		// If a user has submitted form data:
		if (!empty($this->data)) {
			// First, let's see if there are any users in the database
			// with the username supplied by the user using the form:
			
			$someone = $this->User->findByUserName($this->data['User']['user_name']);
			
			// At this point, $someone is full of user data, or its empty.
			// Let's compare the form-submitted password with the one in
			// the database.
			if(!empty($someone['User']['user_password']) && $someone['User']['user_password'] == md5($this->data['User']['user_password'])) {
				// Note: hopefully your password in the DB is hashed,
				// so your comparison might look more like:
				// md5($this->data['User']['password']) == ...
				
				// This means they were the same. We can now build some basic
				// session information to remember this user as 'logged-in'.
				
				$this->Session->write('User', $someone['User']);
				
				// Write a log Entry
				$this->log("User '" . $someone['User']['user_name'] . "' from ".$this->RequestHandler->getClientIP()." just logged-in.", LOG_DEBUG);
				
				// Now that we have them stored in a session, forward them on
				// to a landing page for the application.
				
				if(isset($this->data['User']['continue'])){				
					$this->redirect($this->data['User']['continue']);
					$this->render();
				}
				$this->redirect('/');
				
			}
			// Else, they supplied incorrect data:
			else {
				// Write a log Entry
				$this->log("Login attempt from ".$this->RequestHandler->getClientIP()."	with user name '".$this->data['User']['user_name'] ."' failed.");
				$this->Session->setFlash('The login credentials you supplied could not be recognized. Please try again.', 'message_error');
				$this->render('login', 'nomenu');
				// Remember the $error var in the view? Let's set that to true:
				//$this->set('error', true);
			}
		}
	}
	
	function logout() {
		// Redirect users to this action if they click on a Logout button.
		// All we need to do here is trash the session information:
		
		// Write a log Entry
		$user = $this->Session->read('User');
		if($user){
			$this->log("User '" . $user['user_name'] . "' from ".$this->RequestHandler->getClientIP()." logged-out.", LOG_DEBUG);
		}
		
		$this->Session->delete('User');
		
		// And we should probably forward them somewhere, too...
		 
		$this->redirect('/');
	}
	
	function index() {
		$this->checkSession();
		$userInfo = $this->Session->read('User');
		if($userInfo['user_admin']){
			$this->redirect('/admin/users/');
		} else {
			$user_id = $userInfo['id']; 
			$this->redirect('/users/view/'.$user_id);
		} 
	}
	
	function view($id = null) {
		$this->checkSession();
		$this->checkMalformedUrl();
		$this->checkRecordExistance($id);
		$this->set('user', $this->User->read(null, $id));
	}
	
	function update($id = null) {
		$this->checkSession();
		$userInfo = $this->Session->read('User');
		if($userInfo['user_name'] == "root"){
			$this->redirect('/admin/users/update/'.$id);
		} 
		$this->checkAccess($id, 'update');
		if(empty($this->data)) {
			$this->checkRecordExistance($id);
			$users = $this->User->read(null, $id);
			$users['User']['user_password'] = "";
			$this->data = $users; 
		} else {
			// To prevent user_name modification by any malpractice
			$this->data['User']['user_name'] = $this->User->field('user_name', "id =".$id);
			$this->cleanupData();
			$this->User->begin();
			$this->data['User']['old_password'] = md5($this->data['User']['old_password']);
			$oldPassword = $this->User->field('user_password', array('id' => $id));
			if($oldPassword != $this->data['User']['old_password']) {
				$this->Session->setFlash('Old password does not match records.', 'message_error');
				$this->data['User']['old_password']     = "";
				$this->data['User']['user_password']    = "";
				$this->data['User']['confirm_password'] = "";
				$this->render();
				exit();
			} else {
				if($this->data['User']['user_password'] != $this->data['User']['confirm_password']) {
					$this->Session->setFlash('Passwords do not match', 'message_error');
					$this->data['User']['old_password']     = "";
					$this->data['User']['user_password']    = "";
					$this->data['User']['confirm_password'] = "";
					$this->render();
					exit();
				}					
				//$this->data['User']['user_password'] = md5($this->data['User']['new_password']);
				if($this->User->save($this->data)) {
					$this->User->saveField('user_password', md5($this->data['User']['user_password']));
					$this->User->commit();
					$this->Session->setFlash('The User details has been updated.', 'message_ok');
					$this->redirect('/users/');
				} else {
					$this->User->rollback();
					$this->data['User']['old_password'] = "";
					$this->data['User']['user_password'] = "";
					$this->data['User']['confirm_password'] = "";
					$this->Session->setFlash('Please correct errors below.', 'message_error');
					$this->render();
				}
			}
		}
	}


	function admin_index() {
		$this->checkSession();
		$this->checkAdminAccess();
		$this->checkMalformedUrl();
		list($order, $limit, $page) = $this->setupPagination();
		$this->set('users', $this->User->findAll(NULL, NULL, $order, $limit, $page));
	}

	function admin_view($id = null) {
		$this->checkSession();
		$this->checkAdminAccess();
		$this->checkMalformedUrl();
		$this->checkRecordExistance($id);
		$this->set('user', $this->User->read(null, $id));
	}

	function admin_add() {
		$this->checkSession();
		$this->checkAdminAccess();
		if(empty($this->data)) {
			$this->render();
		} else {
			$this->cleanupData();
			if($this->data['User']['user_password'] != null) {
				if($this->data['User']['user_password'] == $this->data['User']['confirm_password']) {
					//$this->data['User']['user_password'] = md5($this->data['User']['user_password']);
					$this->User->begin();
					if($this->User->save($this->data)) {
						$this->User->saveField('user_password', md5($this->data['User']['user_password']));
						$user_id = $this->User->getLastInsertID();
						$aro = new Aro();
						$aro->create($user_id, null, $this->data['User']['user_name']);
						$aro->setParent('Users', $user_id); 
						$aco = new Aco();
						$aco->create($user_id, null, 'Users'.DS.'view'.DS.$user_id); 
						$aco->create($user_id, null, 'Users'.DS.'update'.DS.$user_id); 
						$this->Acl->allow($user_id, 'Users'.DS.'view'.DS.$user_id, 'read'); 
						$this->Acl->allow($user_id, 'Users'.DS.'update'.DS.$user_id, 'update'); 
						// Write a log Entry
						$currentUser = $this->Session->read('User');
						$currentUserName =  $currentUser ['user_name'];
						$this->log("User '".$currentUserName."' from ".$this->RequestHandler->getClientIP()." created a new user '".$this->data['User']['user_name']."'.", LOG_DEBUG);
						$this->User->commit();
						$this->Session->setFlash('The User has been added.', 'message_ok');
						$this->redirect('/users/');
					} else {
						$this->User->rollback();
						$this->Session->setFlash('Please correct errors below.', 'message_error');
						$this->data['User']['user_password'] = "";
						$this->data['User']['confirm_password'] = "";
						$this->render();
						exit();
					}
				} else {
					$this->Session->setFlash('Passwords do not match.', 'message_error');
					$this->data['User']['user_password'] = "";
					$this->data['User']['confirm_password'] = "";
					$this->render();
					exit();
				} 
			} else {
					$this->User->invalidFields($this->data);
					$this->Session->setFlash('Please correct errors below.', 'message_error');
					$this->data['User']['user_password'] = "";
					$this->data['User']['confirm_password'] = "";
					$this->render();
					exit();
				}
		}
	
	}
	
	function admin_update($id = null) {
		$this->checkSession();
		$this->checkAdminAccess();
		$this->checkMalformedUrl();
		$this->checkRecordExistance($id);
		if(empty($this->data)) {
			$this->checkMalformedUrl();
			$this->checkRecordExistance($id);
			$users = $this->User->read(null, $id);
			$users['User']['user_password'] = "";
			$this->data = $users; 
		} else {
			// To prevent user_name modification by any malpractice
			$this->data['User']['user_name'] = $this->User->field('user_name', "id =".$id);
			$this->cleanupData();
			if($this->data['User']['user_password'] != null) {
				if($this->data['User']['user_password'] == $this->data['User']['confirm_password']) {
					//$this->data['User']['user_password'] = md5($this->data['User']['user_password']);
					$this->User->begin();
					if($this->User->save($this->data)) {
						$this->User->saveField('user_password', md5($this->data['User']['user_password']));
						/*
						$user_id = $this->User->getLastInsertID();
						$aro = new Aro();
						$aro->create($user_id, null, $this->data['User']['user_name']);
						$aro->setParent('Users', $user_id); 
						$aco = new Aco();
						$aco->create($user_id, null, 'Users'.DS.'view'.DS.$user_id); 
						$aco->create($user_id, null, 'Users'.DS.'update'.DS.$user_id); 
						$this->Acl->allow($user_id, 'Users'.DS.'view'.DS.$user_id, 'read'); 
						$this->Acl->allow($user_id, 'Users'.DS.'update'.DS.$user_id, 'update'); 
						*/
						$this->User->commit();
						$this->Session->setFlash('The User has been saved.', 'message_ok');
						$this->redirect('/users/');
					} else {
						$this->User->rollback();
						$this->Session->setFlash('Please correct errors below1.', 'message_error');
						$this->data['User']['user_password'] = "";
						$this->data['User']['confirm_password'] = "";
						$this->render();
						exit();
					}
				} else {
					$this->Session->setFlash('Passwords do mot match.', 'message_error');
					$this->data['User']['user_password'] = "";
					$this->data['User']['confirm_password'] = "";
					$this->render();
					exit();
				} 
			} else {
					$this->User->invalidFields($this->data);
					$this->Session->setFlash('Please correct errors below.', 'message_error');
					$this->data['User']['user_password'] = "";
					$this->data['User']['confirm_password'] = "";
					$this->render();
					exit();
				}
		}
	
	}
	
	function admin_delete($id = null) {
		$this->checkSession();
		$this->checkAdminAccess();
		$this->checkMalformedUrl();
		$this->checkRecordExistance($id);
		$this->User->begin();
		if($id == 1){
			$this->Session->setFlash('Root user cannot be deleted.', 'message_error');
			$this->redirect('/admin/users/index');
		} else {
			if($this->User->del($id)) {
				$this->User->commit();
				$this->Session->setFlash('The User deleted: id '.$id, 'message_ok');
				$this->redirect('/admin/users/index');
			}else {
				$this->User->rollback();
				$this->showError(ERROR_DELETE, 'Unable to delete record.');
			}
		}
	}
	
	function admin_group($id = null) {
		$this->checkSession();
		$this->checkAdminAccess();
		$this->checkMalformedUrl();
		$this->checkRecordExistance($id);
		$userInfo = $this->Session->read('User');
		$user_id = $userInfo['id']; 
		if($id == 1){
			$this->Session->setFlash('Root user privilages cannot be changed.', 'message_error');
			$this->redirect('/admin/users/index');
		} else {
			$adminLevel = $this->User->field('user_admin', "id =".$id);
			$adminLevel = $adminLevel ? 0 : 1;
			$userName   = $this->User->field('user_name', "id =".$id);
			$userPass   = $this->User->field('user_password', "id =".$id);
			$this->User->begin();
			$this->data = $this->User->find(array('User.id'=>$id)); 
			$this->data['User']['user_admin'] = $adminLevel; 
			$this->data['User']['user_password']    = "dummypassword"; 
			$this->data['User']['confirm_password'] = "dummypassword"; 
			//if($this->User->saveField('user_admin', $adminLevel)) {
			if($this->User->save($this->data)) {
				$this->User->saveField('user_password', $userPass);
				$msgStr = $adminLevel ? "added to" : "removed from"; 
				$this->Session->setFlash("User $userName has been " . $msgStr . " the admin group.", 'message_ok');
				// Write a log Entry
				$currentUser = $this->Session->read('User');
				$currentUserName =  $currentUser ['user_name'];
				$this->User->commit();
				$this->log("User '$userName' has been $msgStr the admin group by '$currentUserName'.", LOG_DEBUG);
				$this->redirect('/admin/users/index');
			} else {
				$this->User->rollback();
				$this->Session->setFlash("Unable to change user permissions.", 'message_error');
				$this->redirect('/admin/users/index');
			}
		}
	}
	
	function checkAccess($id, $action){
		$userInfo = $this->Session->read('User');
		$user_id = $userInfo['id']; 
		$user_name = $userInfo['user_name']; 

        $page = $this->name.DS.$this->action;
        $page = $page.DS.$id;
		
        $access = $this->Acl->check($user_id, $page, $action);
        if ($access === false) {
			$url = $this->params['url']['url'];
			$this->log(ERROR_ACCESS_DENIED." Access denied, User:". $user_name . ", IP:".$this->RequestHandler->getClientIP().", Attempt to access forbidden resource '".$url ."'.");
			$this->Session->setFlash('You are not authorised to perform this action.', 'message_error');
			$this->redirect('/pages/access_denied');
            exit;
        } 
	}
	
	function session_timeout(){
		// For displaying session timeout mesage in ajax layouts.
	}
	
	/**
	 *  Function to create initial ACL table data
	 */
	/*
	function init(){
		$aro = new Aro();
		$aro->create(0, null, 'Admins'); // group
		$aro->create(0, null, 'Users'); //group 
		$user_id = 1;
		$aro->create($user_id, null, 'admin');
		$aro->setParent('Admins', $user_id); 
		$aco = new Aco();
		$aco->create($user_id, null, 'Users'.DS.'view'.DS.$user_id); 
		$aco->create($user_id, null, 'Users'.DS.'update'.DS.$user_id); 
		$this->Acl->allow($user_id, 'Users'.DS.'view'.DS.$user_id, 'read'); 
		$this->Acl->allow($user_id, 'Users'.DS.'update'.DS.$user_id, 'update'); 
		$this->Session->setFlash('ACL Table initialised');
		$this->redirect('/users/');
	}
	 */
	
}
?>